<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>司机信息列表</title>
    <link rel="stylesheet" href="/css/styles.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            getCarList(0);
        });

        function showDriverInfo(btn) {
            var tr = btn.parentNode.parentNode;
            var tds = tr.getElementsByTagName('td');
            var name = tds[0].innerText;
            var phone = tds[1].innerText;
            var licenseNum = tds[2].innerText;
            alert(
                "司机姓名：" + name + "\n" +
                "电话：" + phone + "\n" +
                "车牌号：" + licenseNum
            );
        }

        function getCarList(code){
            if(code==0){
                $.ajax({
                    url: '/breed/mobile/product/sell/headList',
                    type: 'GET',
                    data: {},
                    success: function(nextRes) {
                        // nextRes 是一个 JSON 数组
                        var dataList = nextRes;
                        // 如果后端没加@ResponseBody，可能需要 JSON.parse(nextRes)
                        if(typeof dataList === "string"){
                            dataList = JSON.parse(nextRes);
                        }
                        var tbody = '';
                        window._carDetailLists = dataList.map(function(item) {
                            return item.detailList || [];
                        });
                        for(var i=0; i<dataList.length; i++){
                            var item = dataList[i];
                            tbody += '<tr data-standard-num="' + (item.standardNum || '') + '" data-surplus-frame-num="' + (item.surplusFrameNum || '') + '">' +
                                '<td>' + (item.driverName || '') + '</td>' +
                                '<td>' + (item.telePhone || '') + '</td>' +
                                '<td>' + (item.licenseNum || '') + '</td>' +
                                '<td><a href="javascript:void(0);" onclick="showSignInDetail(\'' + (item.createDateTime || '') + '\', \'' + (item.driverName || '') + '\', \'' + (item.standardNum || '') + '\', \'' + (item.surplusFrameNum || '') + '\')">' + (item.createDateTime || '') + '</a></td>' +
                                '<td>' + (item.customerName || '') + '</td>' +
                                '<td>' + (item.surplusFrameNum || '') + '</td>' +
                                '<td>' + (item.standardNum || '') + '</td>' +
                                '<td><button class="btn" onclick="showLoadInfo(' + i + ')">装车信息</button></td>' +
                                '</tr>';
                        }
                        $('#carListTable tbody').html(tbody);
                        $('#carListContainer').show();
                    }
                });
            }else {
                alert("code不等于0")
            }
        }

        function signInDriver(btn) {
            var tr = btn.parentNode.parentNode;
            var tds = tr.getElementsByTagName('td');
            var driver = tds[0].innerText;
            var telephone = tds[1].innerText;
            var licenseNum = tds[2].innerText;
            var sourSeqNo = tds[3].innerText;
            var code;
            $.ajax({
                url: '/breed/mobile/product/proSellVehicle/addSellVehicle',
                type: 'POST',
                data: {
                    driver: driver,
                    licenseNum: licenseNum,
                    telephone: telephone,
                    sourSeqNo:sourSeqNo
                },
                success: function(res) {
                    alert(JSON.parse(res).message);
                    code = JSON.parse(res).code;
                    getCarList(code)
                },
                error: function(xhr) {
                    alert('签到失败：' + xhr.responseText);
                }
            });
        }

        function showSignInDetail(createDateTime, driverName, standardNum, surplusFrameNum) {
            $.ajax({
                url: '/breed/mobile/chicken/common/getProDuctHouse',
                type: 'GET',
                data: {},
                success:function(req){
                    var dataList = req;
                    if(typeof dataList === "string"){
                        dataList = JSON.parse(req);
                    }
                    var tbody = '';
                    for(var i=0; i<dataList.length; i++){
                        var item = dataList[i];
                        tbody += '<tr>' +
                            '<td style="display:none;">' + (item.orgId || '') + '</td>' +
                            '<td><a href="javascript:void(0);" onclick="sendHouseInfo(this)">' + (item.houseCode || '') + '</a></td>' +
                            '<td style="display:none;">' + (item.houseId || '') + '</td>' +
                            '<td style="max-width:120px; white-space:nowrap; overflow-x:auto; display:block;">' + (item.houseName || '') + '</td>' +
                            '<td>' + (item.invQty || '') + '</td>' +
                            '<td>' + (item.batch || '') + '</td>' +
                            '<td>' + (item.day || '') + '</td>' +
                            '<td style="display:none;">' + (item.itemCode || '') + '</td>' +
                            '<td>' + (item.itemName || '') + '</td>' +
                            '<td style="display:none;">' + (item.stockSeqNo || '') + '</td>' +
                            '</tr>';
                    }
                    $('#modalDriverName').text('司机姓名：' + driverName);
                    $('#modalCreateDateTime').text('签到时间：' + createDateTime);
                    $('#modalHouseTableBody').html(tbody);
                    $('#modalHouseInfo').text("");
                    $('#signInDetailModal').data('standard-num', standardNum);
                    $('#signInDetailModal').data('surplus-frame-num', surplusFrameNum);
                    $('#signInDetailModal').show();
                },
                error:function(xhr){
                    $('#modalHouseTableBody').html("");
                    $('#modalHouseInfo').text('栋舍信息获取失败');
                    $('#signInDetailModal').show();
                }
            });
        }

        function closeSignInDetail() {
            $('#signInDetailModal').hide();
        }

        function sendHouseInfo(aTag) {
            var tr = $(aTag).closest('tr');
            var tds = tr.find('td');
            // 读取 standardNum
            var standardNum = $('#signInDetailModal').data('standard-num') || '';
            var surplusFrameNum = $('#signInDetailModal').data('surplus-frame-num') || '';
            // 保存参数到window临时变量，供三级弹窗提交用
            window._houseInfoToSend = {
                orgId: tds.eq(0).text(),
                houseCode: tds.eq(1).text(),
                houseId: tds.eq(2).text(),
                houseName: tds.eq(3).text(),
                invQty: tds.eq(4).text(),
                batch: tds.eq(5).text(),
                day: tds.eq(6).text(),
                itemCode: tds.eq(7).text(),
                itemName: tds.eq(8).text(),
                stockSeqNo: tds.eq(9).text()
            };
            // 设置默认值
            $('#standardNumInput').val(standardNum);
            $('#boxNumInput').val(surplusFrameNum);
            $('#sumNumInput').val("");
            $('#fractionInput').val(0);
            calcSumNum();
            $('#thirdLevelModal').show();
        }

        function closeThirdLevel() {
            $('#thirdLevelModal').hide();
        }

        function calcSumNum() {
            var boxNum = parseInt($('#boxNumInput').val()) || 0;
            var standardNum = parseInt($('#standardNumInput').val()) || 0;
            var fraction = parseInt($('#fractionInput').val()) || 0;
            var sumNum = boxNum * standardNum + fraction;
            $('#sumNumInput').val(sumNum);
        }

        function submitThirdLevel() {
            var boxNum = $('#boxNumInput').val();
            var standardNum = $('#standardNumInput').val();
            var sumNum = $('#sumNumInput').val();
            var fraction = $('#fractionInput').val();
            var houseInfo = window._houseInfoToSend;

            var dataToSend = {
                houseInfo: houseInfo,
                boxNum: boxNum ? parseInt(boxNum) : null,
                fraction: fraction ? parseInt(fraction) : null,
                standardNum: standardNum ? parseInt(standardNum) : null,
                sumNum: sumNum ? parseInt(sumNum) : null
            };

            $.ajax({
                url: '/breed/mobile/product/sell/add',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(dataToSend),
                success: function(res) {
                    alert(res);
                    code = JSON.parse(res).code;
                    // alert(code);
                    getCarList(code);//卖完鸡后更新可装存栏
                    closeThirdLevel();
                    $('#signInDetailModal').hide();//隐藏二级页面
                },
                error: function(xhr) {
                    alert('发送失败：' + xhr.responseText);
                }
            });
        }

        function showLoadInfo(index) {
            var detailList = window._carDetailLists[index] || [];
            var tbody = '';
            for (var i = 0; i < detailList.length; i++) {
                var item = detailList[i];
                tbody += '<tr>' +
                    '<td>' + (item.houseName || '') + '</td>' +
                    '<td>' + (item.standardNum || '') + '</td>' +
                    '<td>' + (item.boxNum || '') + '</td>' +
                    '<td>' + (item.fraction || '') + '</td>' +
                    '<td>' + (item.sumNum || '') + '</td>' +
                    '</tr>';
            }
            $('#loadInfoTableBody').html(tbody);
            $('#loadInfoModal').show();
        }

        function reverseCalc() {
            var sumNum = parseInt($('#sumNumInput').val()) || 0;
            var standardNum = parseInt($('#standardNumInput').val()) || 0;
            var boxNum = parseInt($('#boxNumInput').val()) || 0;
            if (standardNum > 0) {
                boxNum = Math.floor(sumNum / standardNum);
                var fraction = sumNum % standardNum;
                $('#boxNumInput').val(boxNum);
                $('#fractionInput').val(fraction);
            }
        }

        $(function() {
            // 遮罩点击关闭二级弹窗
            $('#signInDetailModal').on('mousedown', function(e) {
                // 只在点击遮罩本身时关闭，点击内容区不关闭
                if (e.target === this) {
                    closeSignInDetail();
                }
            });
        });
    </script>
</head>
<body>
    <h2>司机信息列表</h2>
    <table>
        <thead>
            <tr>
                <th>司机姓名</th>
                <th>电话</th>
                <th>车牌号</th>
                <th>计划ID</th>
                <!-- <th>装车信息</th> -->
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="driver : ${driverList}">
                <td th:text="${driver.driverName}">司机姓名</td>
                <td th:text="${driver.telePhone}">电话</td>
                <td th:text="${driver.licenseNum}">车牌号</td>
                <td th:text="${driver.sourSeqNo}">计划id</td>
                <!-- <td><button class="btn" onclick="showLoadInfo(' + i + ')">装车信息</button></td> -->
                <td>
                    <button class="btn" onclick="showDriverInfo(this)">详情</button>
                    <button class="btn" style="background:#2196F3;margin-left:8px;" onclick="signInDriver(this)">签到</button>
                </td>
            </tr>
        </tbody>
    </table>

    <!-- 展示车辆签到后的列表 -->
    <div id="carListContainer" >
        <table id="carListTable" border="1">
            <thead>
                <tr>
                    <th>司机</th>
                    <th>电话</th>
                    <th>车牌号</th>
                    <th>签到时间</th>
                    <th>客户</th>
                    <th>可装车数量</th>
                    <th>每框只数</th>
                    <th>装车信息</th>
                </tr>
            </thead>
            <tbody>
                <!-- 动态插入 -->
            </tbody>
        </table>
    </div>

    <!-- 二级弹窗，初始隐藏 -->
    <div id="signInDetailModal" style="display:none; position:fixed; left:0; top:0; width:100vw; height:100vh; background:rgba(0,0,0,0.3); z-index:9999;">
        <div id="signInDetailContent" style="background:#fff; margin:100px auto; width:700px; border-radius:8px; box-shadow:0 2px 8px #888; padding:20px; position:relative; max-height:80vh; overflow:auto;">
            <h3>签到详情</h3>
            <p id="modalDriverName"></p>
            <p id="modalCreateDateTime"></p>
            <table id="modalHouseTable" border="1" style="width:100%;margin-top:10px;">
                <thead>
                    <tr>
                        <th style="display:none;">机构代码</th>
                        <th>栋舍代码</th>
                        <th style="display:none;">栋舍ID</th>
                        <th>栋舍名称</th>
                        <th>存栏数量</th>
                        <th>批次</th>
                        <th>日龄</th>
                        <th style="display:none;">品种代码</th>
                        <th>品种名字</th>
                        <th style="display:none;">StockSeqNo</th>
                    </tr>
                </thead>
                <tbody id="modalHouseTableBody">
                    <!-- 动态插入 -->
                </tbody>
            </table>
            <div id="modalHouseInfo" style="color:red;"></div>
            <button onclick="closeSignInDetail()">关闭</button>
        </div>
    </div>

    <!-- 三级弹窗，初始隐藏 -->
    <div id="thirdLevelModal" style="display:none; position:fixed; left:0; top:0; width:100vw; height:100vh; background:rgba(0,0,0,0.3); z-index:10000;">
        <div style="background:#fff; margin:120px auto; width:350px; border-radius:8px; box-shadow:0 2px 8px #888; padding:24px; position:relative;">
            <h3>填写参数</h3>
            <form id="thirdLevelForm">
                <div style="margin-bottom:12px;">
                    <label>可装车框数(boxNum)：</label>
                    <input type="number" id="boxNumInput" name="boxNum" style="width:120px;" oninput="calcSumNum()" />
                </div>
                <div style="margin-bottom:12px;">
                    <label>每框只数(standardNum)：</label>
                    <input type="number" id="standardNumInput" name="standardNum" style="width:120px;" oninput="calcSumNum()" />
                </div>
                <div style="margin-bottom:12px;">
                    <label>零头数(fraction)：</label>
                    <input type="number" id="fractionInput" name="fraction" style="width:120px;" oninput="calcSumNum()" value="0" />
                </div>
                <div style="margin-bottom:12px;">
                    <label>合计只数(sumNum)：</label>
                    <input type="number" id="sumNumInput" name="sumNum" style="width:120px;" oninput="reverseCalc()" />
                </div>
                <div style="text-align:right;">
                    <button type="button" onclick="submitThirdLevel()" class="btn">确认</button>
                    <button type="button" onclick="closeThirdLevel()" class="btn" style="background:#aaa;margin-left:8px;">取消</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 新增装车信息弹窗，初始隐藏 -->
    <div id="loadInfoModal" style="display:none; position:fixed; left:0; top:0; width:100vw; height:100vh; background:rgba(0,0,0,0.3); z-index:10001;">
        <div style="background:#fff; margin:120px auto; width:600px; border-radius:8px; box-shadow:0 2px 8px #888; padding:24px; position:relative; max-height:80vh; overflow:auto;">
            <h3>装车信息</h3>
            <table id="loadInfoTable" border="1" style="width:100%;margin-top:10px;">
                <thead>
                    <tr>
                        <th>栋舍名称</th>
                        <th>标准只数</th>
                        <th>箱数</th>
                        <th>零头</th>
                        <th>合计</th>
                        <!-- 可根据 SalesChickenDetail 字段继续添加 -->
                    </tr>
                </thead>
                <tbody id="loadInfoTableBody">
                    <!-- 动态插入 -->
                </tbody>
            </table>
            <div style="text-align:right;margin-top:10px;">
                <button onclick="$('#loadInfoModal').hide()" class="btn">关闭</button>
            </div>
        </div>
    </div>
</body>
</html>